package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.common.Des3Util;
import com.antdesignbackend.backend.common.GoogleAuthenticator;
import com.antdesignbackend.backend.common.returnResult.ReturnCode;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.config.WebConfig;
import com.antdesignbackend.backend.entity.Users;
import com.antdesignbackend.backend.entity.entityVo.UserRoleVo;
import com.antdesignbackend.backend.service.ILogService;
import com.antdesignbackend.backend.service.UserRolesService;
import com.antdesignbackend.backend.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
public class LoginController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    UserService userService;
    @Autowired
    UserRolesService userRolesService;
    @Autowired
    ILogService logService;
    /**
     * 跳转登录页
     *
     * @return
     */
    @GetMapping(value = "/login")
    public String login() {
        return "login";
    }

    @GetMapping(value = "/error404")
    public String error404() {
        return "404";
    }

    @GetMapping(value = "/error")
    public String error() {
        return "404";
    }

    @GetMapping(value = "/error500")
    public String error500() {
        return "500";
    }

    /**
     * 验证登录请求
     *
     * @param loginName
     * @param password
     * @param request
     * @return
     */
    @PostMapping(value = "/checkLogin")
    @ResponseBody
    public ReturnVO checkLogin(String loginName, String password,String code, HttpServletRequest request) throws Exception {

        try {
            password = Des3Util.decode(password);
            //验证用户名密码是否正确
            QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("UserName", loginName).
                    eq("Password", DigestUtils.md5DigestAsHex(password.getBytes())).
                    eq("activity", 1);
            Users users = userService.getOne(queryWrapper);

            if (users != null) {

                    //查询角色信息
                    List<UserRoleVo> userRoleVos = userRolesService.selectUserRoleList(
                            new QueryWrapper<UserRoleVo>().eq("UserName", loginName).
                                    eq("Password", DigestUtils.md5DigestAsHex(password.getBytes())), null);
                    //获取角色ID
                    StringBuilder roles = new StringBuilder();
                    StringBuilder roleCheckKeys = new StringBuilder();
                    for (UserRoleVo userRoleVo : userRoleVos) {
                        roles.append(userRoleVo.getRoleID()).append(",");
                        //记录roles表checkName，用来注解判断角色是否允许
                        roleCheckKeys.append(userRoleVo.getRoleCheckName()).append(",");
                    }

                    roles = new StringBuilder(roles.substring(0, roles.length() - 1));
                    roleCheckKeys = new StringBuilder(roleCheckKeys.substring(0, roleCheckKeys.length() - 1));

                    HttpSession session = request.getSession();
                    //判断用户名密码是否正确,用户名当作key
                    session.setAttribute("LoginName", loginName);
                    session.setAttribute("RoleID", roles.toString());
                    session.setAttribute("RoleCheckKey", roleCheckKeys.toString());
                    session.setAttribute("Key", users.getKeyName());
                    session.setAttribute("RoleName", userRoleVos.get(0).getRoleName());
                    session.setAttribute("UserType", userRoleVos.get(0).getUserType());
                    session.setAttribute("UserID", userRoleVos.get(0).getUserID());

                    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    logger.info(loginName + ":登录成功，登录时间" + df.format(new Date()));
                    logService.WriteLog(100, "系统登录成功", loginName);
                    //组装返回js数据
                    ReturnVO returnVO = new ReturnVO();
                    returnVO.setCode("200");
                    Map<String, String> map = new HashMap<>();
                    map.put("LoginName", loginName);
                    map.put("RoleID", roles.toString());
                    map.put("RoleName", userRoleVos.get(0).getRoleName());
                    map.put("UserType", String.valueOf(userRoleVos.get(0).getUserType()));
                    map.put("UserID", String.valueOf(userRoleVos.get(0).getUserID()));
                    returnVO.setData(map);
                    return returnVO;


            } else {
                return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");

            }
        }
        catch(Exception ex)
        {
            return new ReturnVO(ReturnCode.VerificationFailed, "登录失败");
        }



    }


    public static void main(String[] arg) {
        //比如对密码进行 md5 加密
        //1、加密之后你也不知道原始密码是什么的，只能通过密文比对的。认可这种方式用DigestUtils下面的加密方法，这个是spring 自带的
        //前端段加密解密的使用。后台使用Des3Util；前端js使用C_Des3
        String md5Pass = DigestUtils.md5DigestAsHex("123456_123456".getBytes());
        System.out.println(md5Pass);
    }
}
